<?php

namespace App\Logic\Order;

use App\Core\BaseCore;
use App\Core\BaseModel;
use App\Core\Exception\DefaultException;
use App\Core\Output;
use App\Logic\Order\Form\OrderTaskStatisticsListForm;
use App\Model\Member\MemberProfitStatisticsModel;
use App\Model\Order\OrderTaskModel;
use App\Model\Order\OrderTaskStatisticsModel;
use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Singleton;
use EasySwoole\Http\Request;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\RedisPool\RedisPool;
use Throwable;

class OrderTaskStatisticsService extends BaseCore
{

    use Singleton;

    /**
     * 字典数据
     * @param $data
     * @return Output
     * @throws Exception
     * @throws Throwable
     */
    public function getDict(Request $request) : Output
    {
        $result = [
            'type'   => ArrayHelper::keyArrayToList(MemberProfitStatisticsModel::getTypeDict()),
        ];

        return $this->success($result);
    }

    /**
     * 每日订单任务汇总列表 getLists
     * @param Request $request
     * @return Output
     * @throws DefaultException
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     */
    public function getLists(Request $request){
        $params    = $request->getQueryParams();
        $cache     = RedisPool::defer();
        $cache_key = "orderTaskStatisticsCache:lists:" . json_encode($params + ['_id' => UserIdentityHelper::getId(), '_name' => UserIdentityHelper::getUsername()]);
        if ($cache_data = $cache->get($cache_key)) { //缓存存在
            $data = json_decode($cache_data, true);
        } else {
            $form = new OrderTaskStatisticsListForm($params, $request);
            $data = $form->lists();
            $cache->set($cache_key, json_encode($data), BaseModel::CACHE_EXPIRE);
        }
        return $this->success($data);
    }
    /**统计最近10天数据*/
    public function statistics()
    {
        if((date('Hi') - 0) < 330){
            return false;
        }

        $tableorder_task = OrderTaskModel::create()->getTableName();
        $table = OrderTaskStatisticsModel::create()->getTableName();
        $startDate = date('Y-m-01', strtotime("-". OrderTaskStatisticsModel::STATISTICS_BEFORE_DAY ." day"));
        try {
            DbManager::getInstance()->startTransactionWithCount('write');
            $data = [];
            /** 新的idx_key
             * SELECT * FROM (
             * SELECT
             * CONCAT(DATE(created_at), '-', user_id) AS `idx_key`,
             * DATE(created_at) AS `task_date`,
             * user_id,
             * SUM(quantity) AS `quantity`,
             * SUM(order_amount) AS `order_amount`,
             * SUM(finished_order_count) AS `finished_order_count`,
             * SUM(total_user_profit) AS `total_user_profit`
             * FROM ss_order_task
             * WHERE created_at > '2024-11-23'
             * GROUP BY DATE(created_at), user_id
             * ) AS `ts`
             * WHERE ts.idx_key NOT IN (
             * SELECT idx_key FROM ss_order_task_statistics
             * )
            */
            $sql = "SELECT * FROM (
                        SELECT 
                            CONCAT(DATE(created_at), '-', user_id) AS `idx_key`, 
                            DATE(created_at) AS `task_date`, 
                            user_id, 
                            SUM(quantity) AS `quantity`, 
                            SUM(order_amount) AS `order_amount`, 
                            SUM(finished_order_count) AS `finished_order_count`, 
                            SUM(total_user_profit) AS `total_user_profit` 
                        FROM {$tableorder_task} 
                        WHERE created_at > '{$startDate}' 
                        GROUP BY DATE(created_at), user_id
                    ) AS `ts`
                    WHERE ts.idx_key NOT IN (
                        SELECT idx_key FROM {$table}
                    )";

            $queryBuild = new QueryBuilder();
            $queryBuild->raw($sql);
            $result = DbManager::getInstance()->query($queryBuild, true);

            if ($staRes = $result->getResult()) {
                foreach ($staRes as $item) {
                    $data[] = [
                        'idx_key'              => $item['idx_key'],
                        'task_date'            => $item['task_date'],
                        'user_id'              => $item['user_id'],
                        'quantity'             => $item['quantity'],
                        'order_amount'         => $item['order_amount'],
                        'finished_order_count' => $item['finished_order_count'],
                        'total_user_profit'    => $item['total_user_profit'],
                    ];
                }
            }

            /**已有idx_key的数据,删除旧数据,插入新数据
             * SELECT os.id, ts.* FROM (
             * SELECT CONCAT(DATE(created_at), '-', user_id) `idx_key`, DATE(created_at) `task_date`, user_id, SUM(quantity) `quantity`, SUM(order_amount) `order_amount`, SUM(finished_order_count) `finished_order_count`, SUM(total_user_profit) `total_user_profit` FROM ss_order_task WHERE created_at>'2024-11-23' GROUP BY DATE(created_at), user_id
             * ) `ts`
             * INNER JOIN
             * ss_order_task_statistics `os` ON ts.idx_key=os.idx_key AND (ts.quantity!=os.quantity OR ts.order_amount!=os.order_amount OR ts.finished_order_count!=os.finished_order_count OR ts.total_user_profit!=os.total_user_profit)
             * */
            $sql = "SELECT os.id, ts.* FROM (
                        SELECT CONCAT(DATE(created_at), '-', user_id) `idx_key`, DATE(created_at) `task_date`, user_id, SUM(quantity) `quantity`, SUM(order_amount) `order_amount`, SUM(finished_order_count) `finished_order_count`, SUM(total_user_profit) `total_user_profit` FROM {$tableorder_task} WHERE created_at>'{$startDate}' GROUP BY DATE(created_at), user_id
                    ) `ts`
                    INNER JOIN 
                    {$table} `os` ON ts.idx_key=os.idx_key AND (ts.quantity!=os.quantity OR ts.order_amount!=os.order_amount OR ts.finished_order_count!=os.finished_order_count OR ts.total_user_profit!=os.total_user_profit)";

            $queryBuild = new QueryBuilder();
            $queryBuild->raw($sql);
            $result = DbManager::getInstance()->query($queryBuild, true);

            if ($staRes = $result->getResult()) {
                foreach ($staRes as $item) {
                    $data[] = [
                        'idx_key'              => $item['idx_key'],
                        'task_date'            => $item['task_date'],
                        'user_id'              => $item['user_id'],
                        'quantity'             => $item['quantity'],
                        'order_amount'         => $item['order_amount'],
                        'finished_order_count' => $item['finished_order_count'],
                        'total_user_profit'    => $item['total_user_profit'],
                    ];
                }
                /**删除旧数据*/
                $ids = array_column($staRes, 'id');
                OrderTaskStatisticsModel::create()->connection('write')->destroy(['id' => [$ids, 'in']]);
            }
            if(!empty($data)){
                /**插入新数据*/
                OrderTaskStatisticsModel::insertMulti($data);
            }

            DbManager::getInstance()->commitWithCount('write');
            return true;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '统计订单任务错误');
            throw $e;
        }

    }


}
